package site.teamo.biu.flink.web.controller;

import cn.hutool.cache.Cache;
import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import site.teamo.biu.flink.web.annotation.Validation;
import site.teamo.biu.flink.web.configuration.user.UserConfiguration;
import site.teamo.biu.flink.web.controller.model.BiuJSONResult;
import site.teamo.biu.flink.web.controller.model.user.ChangePasswordRequest;
import site.teamo.biu.flink.web.controller.model.user.LoginRequest;
import site.teamo.biu.flink.web.exception.BiuResponseCode;
import site.teamo.biu.flink.web.service.UserService;
import site.teamo.biu.flink.web.util.BiuJSONResultUtils;

import javax.annotation.Resource;

/**
 * @author haocongshun
 * @date 2023/10/30 10:28:21
 */
@Api(tags = "用户认证")
@RestController
@RequestMapping("/api/passport")
public class UserController {

    @Resource(name = "userServiceImpl")
    private UserService userService;

    @Resource
    private Cache<String, String> session;

    @ApiOperation(value = "登录")
    @Validation
    @PostMapping("/login")
    public BiuJSONResult login(@RequestBody LoginRequest request) {
        if (!userService.verify(request.getUsername(), request.getPassword())) {
            return BiuJSONResultUtils.error(BiuResponseCode.LOGIN_FAILED);
        }
        String token = IdUtil.randomUUID();
        session.put(token, request.getUsername());
        return BiuJSONResultUtils.ok(token);
    }

    @ApiOperation("是否登录")
    @PostMapping("/is-login")
    public BiuJSONResult isLogin(@RequestHeader(UserConfiguration.TOKEN_HEADER_NAME) String token) {
        return BiuJSONResultUtils.ok(session.containsKey(token));
    }

    @ApiOperation("修改密码")
    @PostMapping("/change-password")
    public BiuJSONResult isLogin(@RequestAttribute(UserConfiguration.USERNAME_ATTRIBUTE_NAME) String username,
                                 @RequestBody ChangePasswordRequest request) {
        return BiuJSONResultUtils.ok(userService.changePassword(username, request.getOldPassword(), request.getNewPassword()));
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public BiuJSONResult logout(@RequestHeader(UserConfiguration.TOKEN_HEADER_NAME) String token) {
        session.remove(token);
        return BiuJSONResultUtils.ok(true);
    }

}
